﻿//文件指定编译编码UTF-8
#pragma execution_character_set("utf-8")

/**
*    @file:    mainwindow.cpp
*    @brief:
*    @author:  sanshi522@163.com
*    @date:    2024-11-29  11:47
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButtonConnect, &QPushButton::clicked, this, &MainWindow::on_pushButtonConnect_clicked);
    connect(ui->pushButtonSend, &QPushButton::clicked, this, &MainWindow::on_pushButtonSend_clicked);
    connect(&m_webSocket, &QWebSocket::connected, this, &MainWindow::onConnected);
    connect(&m_webSocket, &QWebSocket::disconnected, this, &MainWindow::onDisconnected);
    connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &MainWindow::onTextMessageReceived);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButtonConnect_clicked()
{
    if(m_webSocket.isValid()){
        m_webSocket.close();
    }else{
        QString url = ui->lineEditURL->text();
        if (!url.isEmpty()) {
            m_webSocket.open(QUrl(url));
        }
    }

}

void MainWindow::on_pushButtonSend_clicked()
{
    QString message = ui->lineEditMessage->text();
    if (!message.isEmpty()) {
        m_webSocket.sendTextMessage(message);
        ui->textBrowserLog->append("Send: " + message);
        ui->lineEditMessage->clear();
    }
}

void MainWindow::onConnected()
{
    ui->pushButtonConnect->setText("断开");
    ui->textBrowserLog->append("Connected to server.");
}

void MainWindow::onDisconnected()
{
    ui->pushButtonConnect->setText("连接");
    ui->textBrowserLog->append("Disconnected from server.");
}

void MainWindow::onTextMessageReceived(const QString &message)
{
    if(message.size() > ui->msgMaxLen->value() ){
        ui->textBrowserLog->append(QString("Received:(len:%1)").arg(message.size()) + message.left(100) + "..." );
    }else{
        ui->textBrowserLog->append(QString("Received:(len:%1)").arg(message.size()) + message);
    }
}

void MainWindow::on_clearButton_clicked()
{
    ui->textBrowserLog->clear();
}
